<template>
  <div class="emp-detail">
    <Form :label-width="100" :model="detailList" :rules="ruleValidate" ref="detailRef">
      <Row :gutter="16" type="flex">
        <template v-for="key in keys">
          <Col span="12" :key="key">
            <Form-item :prop="key" :label="$t(`module.employee.${key}`)" :key="key">
              <div v-if="isDate(key)">
                <DatePicker
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  type="date"
                  style="width: 352px;"
                  :transfer="true"
                />
              </div>
              <div v-else-if="key === 'enabled'">
                <Select v-model="detailList[key]" style="width: 352px;" :disabled="!isEdit">
                  <Option v-for="item in [0, 1]" :value="item" :key="item">
                    {{
                    item == 1 ? $t("common.enable") : $t("common.disable")
                    }}
                  </Option>
                </Select>
              </div>
              <div v-else-if="key === 'sex'">
                <Select v-model="detailList[key]" style="width: 352px;" :disabled="!isEdit">
                  <Option v-for="item in ['F', 'M']" :value="item" :key="item">
                    {{
                    item == "F" ? $t("common.woman") : $t("common.man")
                    }}
                  </Option>
                </Select>
              </div>
              <div v-else-if="key === 'idType'">
                <Select v-model="detailList[key]" style="width: 352px;" :disabled="!isEdit">
                  <Option
                    v-for="item in idTypes"
                    :value="item.vsiKey"
                    :key="item.id"
                  >{{ item.vsiValue }}</Option>
                </Select>
              </div>
              <div v-else-if="key === 'employeeNo'">
                <Input
                  :disabled="!isEdit || !!detailList.id"
                  type="text"
                  :maxlength="64"
                  v-model="detailList[key]"
                  :placeholder="`${$t(`module.employee.enter`)}${$t(`module.employee.${key}`)}`"
                />
              </div>
              <div v-else-if="key === 'status'">
                <i-switch v-model="detailList[key]" size="large" :true-value="0" :false-value="1">
                  <span slot="open">{{ $t(`module.employee.incumbent`) }}</span>
                  <span slot="close">{{ $t(`module.employee.dimission`) }}</span>
                </i-switch>
              </div>
              <div v-else-if="key === 'name'">
                <Input
                  :disabled="!isEdit"
                  :maxlength="256"
                  :placeholder="`${$t(`module.employee.enter`)}${$t(`module.employee.${key}`)}`"
                  type="text"
                  v-model="detailList[key]"
                />
              </div>
              <div v-else>
                <Input
                  :disabled="!isEdit"
                  :placeholder="`${$t(`module.employee.enter`)}${$t(`module.employee.${key}`)}`"
                  type="text"
                  v-model="detailList[key]"
                />
              </div>
            </Form-item>
          </Col>
        </template>
      </Row>
    </Form>
    <CommonUserData :disabled="true" :showMainData="true" ref="CommonUserData" :userInfo="detailList"></CommonUserData>
    <FormCreate
      :templateId.sync="detailList.attributeContext"
      templateType="EMPLOYEE"
      :attributeValue="detailList"
      :fApi.sync="fApi"
      :options="fcOption"
      :isEdit="isEdit"
      :selectWidth="'358px'"
    />
  </div>
</template>
<script>
import locales from "./locales.js";
import { modifyEmployee } from "@/api/employeeApi";
import { empBase } from "./keys";
import FormCreate from "@/components/common/FormCreate";
import CommonUserData from "@/components/common/mainUserInfo/CommonUserData";
export default {
  name: "EmployeeDetail",
  mixins: [locales],
  components: { FormCreate, CommonUserData },
  // data: () => ({
  //   detailList: { status: 0 },
  //   fApi: null
  // }),
  data() {
    return {
      detailList: {
        status: 0
      },
      fApi: null
    };
  },
  props: {
    details: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    idTypes: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    actions() {
      const acts = [
        {
          text: this.$t("common.close"),
          handle: () => this.$emit("Close")
        }
      ];
      if (this.isEdit) {
        acts.unshift({
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => this.saveHandler(),
          loading: false
        });
      }

      return acts;
    },
    ruleValidate() {
      const vm = this;

      const validateemployeeNo = (rule, value, callback) => {
        if (value === "") {
          callback(new Error(vm.$t("module.employee.tip.empId")));
        } else if (!new RegExp("^([a-zA-Z0-9]|_|-|\\.)+$").test(value)) {
          callback(new Error(this.$t("module.employee.tip.codeContain")));
        } else if (/[\u4E00-\u9FA5\uF900-\uFA2D]/.test(value)) {
          callback(new Error(vm.$t("module.employee.tip.nozh")));
        } else {
          callback();
        }
      };
      const validPhone = (rule, value, callback) => {
        const reg = /^1[3456789]\d{9}$/;
        if (!value || reg.test(value)) {
          callback();
        } else {
          callback(new Error(vm.$t("module.employee.tip.format")));
        }
      };
      return {
        employeeNo: [
          { required: true, validator: validateemployeeNo, trigger: "blur" },
          { type: "string", max: 64, message: this.$t("module.employee.ruleTips"), trigger: "change" }
        ],
        name: [
          { required: true, message: this.$t("module.employee.tip.chnName"), trigger: "blur" },
          { type: "string", max: 256, message: this.$t("module.employee.ruleTips"), trigger: "change" }
        ],
        mobile: [{ validator: validPhone, trigger: "blur" }],
        email: [{ type: "email", trigger: "blur", message: this.$t("module.employee.tip.format") }]
      };
    },
    keys() {
      return empBase;
    },
    fcOption() {
      return {
        global: {
          "*": {
            col: {
              span: 12
            },
            props: {
              width: "355px",
              disabled: !this.isEdit
            }
          }
        },
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    }
  },
  created() {
    this.$emit("SetPageWidth", 980);
    this.$emit("SetScroll", "auto");
    this.$emit("SetPageActions", this.actions);
  },
  watch: {
    details: {
      handler: function(val) {
        val.idType || (val.idType = this.idTypes[0] && this.idTypes[0].vsiKey);
        this.detailList = { ...val };

        if (!val.id) {
          this.$emit("SetTitle", this.$t(`module.employee.createEmpInfo`));
        } else if (this.isEdit) {
          this.$emit("SetTitle", this.$t(`module.employee.editEmpInfo`));
        } else {
          this.$emit("SetTitle", this.$t(`module.employee.chnDetail`));
        }
      },
      immediate: true
    }
  },
  methods: {
    saveHandler() {
      if (this.fApi && this.fApi.formData) {
        //拓展属性动态表单验证
        this.fApi.validate(valid => {
          if (valid) {
            this.detailList.attributeValue = this.fApi.formData();
            this.submit();
          }
        });
      } else {
        this.submit();
      }
    },
    async submit() {
      this.$refs["detailRef"].validate(async valid => {
        if (valid) {
          this.actions[0].loading = true;
          try {
            this.formatDate(this.detailList);
            let mainInfo = this.$refs['CommonUserData'].getInfo()
            const newFormData = {};
            if (this?.fApi?.formData) {
              const formData = this.fApi.formData();
              const rules = this.fApi.rule;
              for (const r of rules) {
                newFormData[r.matchColumn] = r.type === 'checkbox'
                  ? JSON.stringify(formData[r.field])
                  : formData[r.field];
              }
            }
            await modifyEmployee({...this.detailList, ...mainInfo, ...newFormData});
            this.$message.success(this.$t(`common.${this.detailList.id ? "updateSuccess" : "createSuccess"}`));
            this.$emit("Close", true);
          } catch (error) {
            this.actions[0].loading = false;
          }
        } else {
          // this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    // async saveHandler() {
    //   if (this.fApi && this.fApi.formData) {
    //     this.detailList.attributeValue = this.fApi.formData();
    //     // 如果为当前的拓展属性为空模板，则不校验动态表单
    //     if(Object.keys(this.detailList.attributeValue) > 0) {
    //       const extendValid = await this.validExtendAttr();
    //       if (extendValid === 0) return;
    //     }
    //   }
    //   this.$refs["detailRef"].validate(async valid => {
    //     if (valid) {
    //       this.actions[0].loading = true;
    //       try {
    //         this.formatDate(this.detailList);
    //         await modifyEmployee(this.detailList);
    //         this.$message.success(this.$t(`common.${this.detailList.id ? "updateSuccess" : "createSuccess"}`));
    //         this.$emit("Close", true);
    //       } catch (error) { this.actions[0].loading = false; }
    //     } else {
    //       // this.$message.error(this.$t("common.formValidateFailed"));
    //     }
    //   });
    // },
    // validExtendAttr() {
    //   const { fApi } = this;
    //   return new Promise(resolve => {
    //     fApi.validate(
    //       () => resolve(1),
    //       () => resolve(0)
    //     );
    //   });
    // },
    formatDate(data) {
      const { isDate } = this;
      Object.keys(data).forEach(key => {
        if (isDate(key) && !!data[key]) {
          data[key] = data[key].constructor.toString().includes("Date")
            ? new Date(data[key]).Format("yyyy-MM-dd")
            : data[key];
        }
      });
    },
    isShowKey(key) {
      return empKeys.includes(key);
    },
    isDate(key) {
      return /Dt|Date/.test(key);
    }
  }
};
</script>
<style lang="less">
.emp-detail {
  min-height: auto !important;
  // overflow-y: scroll;
  overflow-x: hidden;
}
</style>
